import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

class AudioPlayerUtils {
  /// 播放器对象
  static final AudioPlayer _player = AudioPlayer();

  ///
  /// 监听音频总时长回调
  ///
  static ValueChanged<Duration>? onAudioTotalDuration;

  ///
  /// 持续更新播放的位置回调
  ///
  static ValueChanged<Duration>? onAudioPositionDuration;

  ///
  /// 音频当前状态
  ///
  static ValueChanged<PlayerState>? onAudioState;

  ///
  /// 音频播放完成回调
  ///
  static VoidCallback? onPlayerComplete;

  /// 初始化播放器
  static void initAudioPlayer() {
    // 音频总时长
    _player.onDurationChanged.listen((event) => onAudioTotalDuration?.call(event));

    // 持续更新播放的位置
    _player.onPositionChanged.listen((event) => onAudioPositionDuration?.call(event));

    // 音频当前状态
    _player.onPlayerStateChanged.listen((event) => onAudioState?.call(event));

    // 音频播放完成。每次音频完成时都会发送事件，因此当音频暂停或停止时不会发送事件
    _player.onPlayerComplete.listen((event) => onPlayerComplete?.call());
  }

  /// 播放
  static Future<void> play(String path) async {
    await _player.stop();
    await _player.play(AssetSource(path));
  }

  /// 暂停
  static Future<void> pause() async {
    await _player.pause();
  }

  /// 恢复播放
  static Future<void> resume() async {
    await _player.resume();
  }

  /// 停止播放
  static Future<void> stop() async {
    await _player.stop();
  }

  /// 拖动到对应时长
  static Future<void> seek(Duration position) async {
    await _player.seek(position);
  }

  /// 释放播放器
  static void dispose() {
    _player.release();
  }
}
